//
//  ViewController.m
//  SocketDemo
//
//  Created by caominglei on 2018/2/2.
//  Copyright © 2018年 caominglei. All rights reserved.
//

#import "ViewController.h"
//socket需要导入的头文件
#import <sys/socket.h>
#import <netinet/in.h>
#import <arpa/inet.h>

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UITextField *ipField;
@property (weak, nonatomic) IBOutlet UITextField *portFiled;
@property (weak, nonatomic) IBOutlet UITextField *sendMsgField;
@property (weak, nonatomic) IBOutlet UILabel *receLabel;

@property (assign, nonatomic) int clientSocket;
@end

@implementation ViewController
- (IBAction)connectClick:(id)sender {
    [self connectIp:self.ipField.text port:[self.portFiled.text intValue]];
}
- (IBAction)sendClick:(id)sender {
    self.receLabel.text = [self sendSndReceMsg:self.sendMsgField.text];
}
- (IBAction)closeClick:(id)sender {
    close(_clientSocket);
    NSLog(@"关闭socket");
}

/**
 接收和发送数据
 */
-(NSString *)sendSndReceMsg:(NSString *)sendMsg
{
    
    //3.向服务器发送数据
    //第一个参数 套接字描述符
    //第二个参数 要发送数据的缓冲区
    //第三个参数 发送数据的字符数
    //第四个参数 是否阻塞 一般都是0
    const char *msg = sendMsg.UTF8String;
    ssize_t sendCount = send(_clientSocket, msg, sizeof(msg), 0);
    NSLog(@"sendCount发送的字符数:%zd",sendCount);
    //接收服务器返回的数据，返回的是实际接收的字节个数
    uint8_t buffer[1024];
    ssize_t receCount = recv(self.clientSocket, buffer, sizeof(buffer), 0);
    NSLog(@"接收的字节数 %zd",receCount);
    //把字节数组转换成字符串
    NSData *data = [NSData dataWithBytes:buffer length:receCount];
    NSString *receMsg = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    return receMsg;
}

- (BOOL)connectIp:(NSString *)ip port:(int)port
{
    //1.创建socket
    //第一个参数 doman 协议簇 指定Ipv4
    //第二个参数 type socket的类型  流socket 数据报socket
    //第三个参数 protocal 协议
    
    //返回值，如果创建成功返回的事socket的描述符，失败-1
    int clientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    self.clientSocket = clientSocket;
    //2.连接服务器-
    //第一个参数 套接字描述符
    //第二个参数 指向数据结构socket的结构体 ip地址和端口号
    //第三个参数 结构体的长度 sizeof
    //返回值 成功0 失败非0
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;//支持ipv4
    addr.sin_addr.s_addr = inet_addr(ip.UTF8String);
    addr.sin_port = htons(port);//网络端口必须是大尾顺序
    int result = connect(clientSocket, (const struct sockaddr *)&addr, sizeof(addr));
    if(result != 0){
        NSLog(@"faild");
        return NO;
    }else{
        NSLog(@"succeed");
        return YES;
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];

    
    
    //打开netcat，模拟服务器->打开终端 nc -lk 12345

}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
